﻿using ScFramework.Core;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PhysicsManager : LogicModuleBase
{
    [RegisterEvent(PhysicsProcessEvent.PhysicsSimulate)]
    void PhysicsSimulate(float delta)
    {
        Physics2D.SyncTransforms();
     //   if(Input.GetKey(KeyCode.Space))
        foreach(var x in GameObject.FindObjectsOfType<HingeJoint2D>())
        {
            Debug.Log($"{x},{x.useLimits}");
        }
        Physics2D.Simulate(delta);
        Dispatch(PhysicsProcessEvent.Physics_RequireComp);

    }

    [RegisterEvent(PhysicsProcessEvent.Physics_ReceiveComp)]
    void SyncDirtyValues(List<SComponent> comps)
    {
        HashSet<ushort> rlist = new HashSet<ushort>();
        foreach(var x in comps)
        {
            if(x is SCollider c)
            {
                if (GameMode.Instance.PosChecker(c.transform.position) == false)
                {
                    rlist.Add(c.AttachedRigidUnion.left());
                }
            }
        }
        foreach(var x in comps)
        {
            bool flag = true;
            if(x is SCollider c)
            {
                if (rlist.Contains(c.AttachedRigidUnion.left()))
                {
                    flag = false;

                }
            }
            else
            {
                if (rlist.Contains(x.EntityId))
                {
                    flag = false;
                }
            }
            for (ushort i = 0; i < x.ValueCnt; i++)
            {
                if (x.IsValuePure(i) == false)
                    if (flag)
                    {
                        x.SetValue(i, x.GetInstanceValue(i));
                    }
                    else
                    {
                        // Debug.Log(x.GetInstanceValue(i) + "|||" + x.GetValue(i));
                        x.SyncValue(i);
                        // x.SetValue(i, x.GetValue(i));    
                    }
            
            }
        }
    }

}
